<template>
  <div>
    <img v-if="imgData != ''" :src="imgData" />
    <div :id="qrid" class="qrcode" v-show="imgData == ''"></div>
  </div>
</template>
<script>
  import QRCode from "qrcodejs2"; // 引入qrcode
  export default {
    name: "QrCodeImg",
    props: ["qrid", "qrContent", "qrWidth", "qrHeight"],
    data() {
      return {
        imgData: ""
      };
    },
    watch: {
      //监听二维码内容值的变化，重新生成二维码
      qrContent: function(val) {
        console.log(val);
        this.qrcode();
      }
    },
    created() {},
    mounted() {
      setTimeout(() => {
        this.qrcode();
      }, 300);
    },
    methods: {
      qrcode() {
        this.$nextTick(() => {
          document.getElementById(this.qrid).innerHTML = ""; //否则每生成一次，上次的还存在，都会多一个二维码
          //要先生成div再生成二维码，否则Cannot read properties of undefined (reading 'appendChild')
          new QRCode(this.qrid, {
            text: this.qrContent,
            //text为转换为二维码的文本，可以是所有东西：图片、文本、电话、链接等等
            width: this.qrWidth, //生成二维码的宽度
            height: this.qrHeight, //生成二维码的高度
            colorDark: "#333333", // 二维码颜色
            colorLight: "#F8F8FF" //二维码背景颜色
          });
        });
        var canvasobj = document.getElementsByTagName("canvas")[0];
        // 将转换后的img标签插入到html中
        var img = this.CanvasToImage(canvasobj);
        this.imgData = img.src;
      },
      CanvasToImage(canvas) {
        //从canvas中提取图片image，新建image对象
        var image = new Image();
        // canvas.toDataURL 返回Base64编码的URL
        // image.src = canvas.toDataURL("image/jpg");
        return image;
      }
    }
  };
</script>
<style lang="scss" scoped>

  div img {
    cursor: pointer;
    transition: all 0.6s;
  }

  div img:hover {
    transform: scale(1.2);
  }
</style>
